package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.model.EducationInfo;
import com.cardbaobao.cardbabyclient.model.IncomeInfo;
import com.cardbaobao.cardbabyclient.model.MemberInfo;
import com.cardbaobao.cardbabyclient.model.WorkType;
import com.cardbaobao.cardbabyclient.ui.pop.SelectorPop;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by jiangzx on 2017/3/31.
 * 个人资料填写
 */
public class PersonMaterialActivity extends BaseActivity {
    private static final int COLOR_BLACK=0xFF222222;

    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.tv_choose_city)
    TextView tvChooseCity;//城市

    @BindView(R.id.tv_highest_education)
    TextView tvHighestEducation;//最高学历

    @BindView(R.id.tv_marry_state)
    TextView tvMarryState;//婚姻状况

    @BindView(R.id.tv_job_information)
    TextView tvJobInformation;//职业信息

    @BindView(R.id.tv_income_range)
    TextView tvIncomeRange;//收入范围

    @BindView(R.id.bt_save)
    Button btSave;

    private MemberInfo memberInfo;

    private String workType;//职业编码
    private String incomeRange;//收入编码
    private String highestEducation;//学历编码
    private String cityId;//城市Id
    private String cityName;//城市名
    private int marriage;//婚姻信息 0 未填 1已婚 2 未婚

    /**学历信息列表*/
    private List<EducationInfo> educationInfoList;
    private SelectorPop educationPop;
    /**婚姻状况列表*/
    private SelectorPop marryPop;
    /**收入信息列表*/
    private List<IncomeInfo> incomeInfoList;
    private SelectorPop incomePop;
    /**职业信息列表*/
    private List<WorkType> workTypeList;
    private SelectorPop workTypePop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId=Self.Page.app_personal_material_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_person_material;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(memberInfo==null){
            loadData();
        }
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x010));
        GoogleAnalyticsUtil.setScreenName(Google.PERSONAL_INFO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==CitySelectActivity.REQUEST_CODE &&resultCode==RESULT_OK&&data!=null){
            this.cityId =data.getStringExtra(CitySelectActivity.RESULT_CITY_ID_KEY);
            this.cityName=data.getStringExtra(CitySelectActivity.RESULT_CITY_NAME_KEY);
            tvChooseCity.setText(cityName);
            tvChooseCity.setTextColor(COLOR_BLACK);
        }
    }

    @OnClick({
            R.id.rl_city_chooser,
            R.id.rl_education_chooser,
            R.id.rl_marry_chooser,
            R.id.rl_job_chooser,
            R.id.rl_income_chooser,
            R.id.bt_save})
    public void onClick(View v){
        switch (v.getId()){
            case R.id.rl_city_chooser:
                initIntent();
                mIntent.setClass(this, CitySelectActivity.class);
                startActivityForResult(mIntent, CitySelectActivity.REQUEST_CODE);
                break;
            case R.id.rl_education_chooser:
                if(null!=educationInfoList&&educationInfoList.size()>0){
                    showEducationPop();
                }
                break;
            case R.id.rl_marry_chooser:
                showMarryPop();
                break;
            case R.id.rl_job_chooser:
                if(workTypeList !=null&& workTypeList.size()>0){
                    showWorkTypePop();
                }
                break;
            case R.id.rl_income_chooser:
                if(incomeInfoList!=null&&incomeInfoList.size()>0){
                    showIncomeRagePop();
                }
                break;
            case R.id.bt_save:
                if(checkInput()){
                    SelfUtils.buriedClickData(Self.Action.app_click_commit_personal_material,
                            Self.Action.app_click_commit_personal_material_des,
                            mEnterPageTime,
                            mCurrentPageId,
                            mPrePageId);
                    GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE,Google.ACTION_PERSONAL_SASE);
                    commitData();
                }
                break;
        }
    }

    /**
     * 根据职业编码返回职业名称
     * @param workTypeCode 职业编码
     * @return 职业名称或者null
     */
    private String getWorkTypeName(String workTypeCode){
        if(TextUtils.isEmpty(workTypeCode)|| workTypeList ==null|| workTypeList.size()==0){
            return null;
        }
        for(int i = 0, size = workTypeList.size(); i<size; i++){
            if(workTypeCode.equals(workTypeList.get(i).getCode())){
                return workTypeList.get(i).getName();
            }
        }
        return null;
    }

    /**
     * 根据学历编码返回学历名称
     * @param educationCode 学历编码
     * @return 学历名称或者null
     */
    private String getEducationName(String educationCode){
        if(TextUtils.isEmpty(educationCode)||null==educationInfoList||educationInfoList.size()==0){
            return null;
        }
        for(int i=0,size=educationInfoList.size();i<size;i++){
            if(educationCode.equals(educationInfoList.get(i).getCode())){
                return educationInfoList.get(i).getName();
            }
        }
        return null;
    }

    /**
     * 根据收入编码返回收入名称
     * @param incomeCode 收入编码
     * @return 收入名称或者null
     */
    private String getIncomeName(String incomeCode){
        if(TextUtils.isEmpty(incomeCode)||null==incomeInfoList||incomeInfoList.size()==0){
            return null;
        }
        for(int i=0,size=incomeInfoList.size();i<size;i++){
            if(incomeCode.equals(incomeInfoList.get(i).getCode())){
                return incomeInfoList.get(i).getName();
            }
        }
        return null;
    }

    /**设置窗体半透明*/
    private void setWindowTranslucent(){
        Window window=getWindow();
        if(window!=null){
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            WindowManager.LayoutParams params=window.getAttributes();
            params.alpha=0.5f;
            window.setAttributes(params);
        }
    }

    /**恢复窗体背景透明度*/
    private void restoreWindowAlpha(){
        Window window=getWindow();
        if(window!=null){
            window.addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            WindowManager.LayoutParams params=window.getAttributes();
            params.alpha=1.0f;
            window.setAttributes(params);
        }
    }

    /**选择最高学历popupWindow*/
    private void showEducationPop(){
        if(null==educationPop){
            List<SelectorPop.PopData> data=new ArrayList<>();
            for(EducationInfo i:educationInfoList){
                data.add(new SelectorPop.PopData(i.getCode(),i.getName()));
            }
            educationPop=new SelectorPop(this, data, new SelectorPop.OnItemClicked() {
                @Override
                public void onClicked(SelectorPop.PopData itemData) {
                    if(itemData!=null){
                        highestEducation=itemData.code;
                        tvHighestEducation.setText(itemData.name);
                        tvHighestEducation.setTextColor(COLOR_BLACK);
                    }
                }
            });
            educationPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    restoreWindowAlpha();
                }
            });
        }
        if(!educationPop.isShowing()){
            educationPop.setCurrentSelected(highestEducation);
            educationPop.showAtLocation(btSave,Gravity.BOTTOM,0,0);
            setWindowTranslucent();
        }
    }

    private void showMarryPop(){
        if(marryPop==null){
            List<SelectorPop.PopData> data = new ArrayList<>();
            data.add(new SelectorPop.PopData("1","已婚"));
            data.add(new SelectorPop.PopData("2","未婚"));
            marryPop=new SelectorPop(mContext, data, new SelectorPop.OnItemClicked() {
                @Override
                public void onClicked(SelectorPop.PopData itemData) {
                    if(itemData!=null){
                        marriage=Integer.valueOf(itemData.code);
                        tvMarryState.setText(itemData.name);
                        tvMarryState.setTextColor(COLOR_BLACK);
                    }else{
                        marriage=0;//未填
                        tvMarryState.setText("请选择婚姻状况");
                    }
                }
            });
            marryPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    restoreWindowAlpha();
                }
            });
        }
        if(!marryPop.isShowing()){
            if(marriage!=0){
                marryPop.setCurrentSelected(String.valueOf(marriage));
            }
            marryPop.showAtLocation(btSave,Gravity.BOTTOM,0,0);
            setWindowTranslucent();
        }
    }

    /**选择收入范围popupWindow*/
    private void showIncomeRagePop(){
        if(null==incomePop){
            List<SelectorPop.PopData> data=new ArrayList<>();
            for(IncomeInfo i:incomeInfoList){
                data.add(new SelectorPop.PopData(i.getCode(),i.getName()));
            }
            incomePop=new SelectorPop(this, data, new SelectorPop.OnItemClicked() {
                @Override
                public void onClicked(SelectorPop.PopData itemData) {
                    if(itemData!=null){
                        incomeRange=itemData.code;
                        tvIncomeRange.setText(itemData.name);
                        tvIncomeRange.setTextColor(COLOR_BLACK);
                    }
                }
            });
            incomePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    restoreWindowAlpha();
                }
            });
        }
        if(!incomePop.isShowing()){
            incomePop.setCurrentSelected(incomeRange);
            incomePop.showAtLocation(btSave, Gravity.BOTTOM, 0, 0);
            setWindowTranslucent();
        }
    }

    /**选择职业信息popupWindow*/
    private void showWorkTypePop(){
        if(null== workTypePop){
            List<SelectorPop.PopData> data=new ArrayList<>();
            for(WorkType i: workTypeList){
                data.add(new SelectorPop.PopData(i.getCode(),i.getName()));
            }
            workTypePop =new SelectorPop(this, data, new SelectorPop.OnItemClicked() {
                @Override
                public void onClicked(SelectorPop.PopData itemData) {
                    if(itemData!=null){
                        workType =itemData.code;
                        tvJobInformation.setText(itemData.name);
                        tvJobInformation.setTextColor(COLOR_BLACK);
                    }
                }
            });
            workTypePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    restoreWindowAlpha();
                }
            });
        }
        if(!workTypePop.isShowing()){
            workTypePop.setCurrentSelected(workType);
            workTypePop.showAtLocation(btSave,Gravity.BOTTOM,0,0);
            setWindowTranslucent();
        }
    }

    /**从上到下检查输入情况，全部填写才可提交*/
    private boolean checkInput(){
        if(TextUtils.isEmpty(cityId)){
            ToastUtil.showToast("请选择所属城市");
            return false;
        }
        if(TextUtils.isEmpty(highestEducation)){
            ToastUtil.showToast("请选择最高学历");
            return false;
        }
        if(marriage==0){
            ToastUtil.showToast("请选择婚姻状况");
            return false;
        }
        if(TextUtils.isEmpty(workType)){
            ToastUtil.showToast("请选择所属职业");
            return false;
        }
        if(TextUtils.isEmpty(incomeRange)){
            ToastUtil.showToast("请选择收入范围");
            return false;
        }
        return true;
    }

    //加载数据
    private void loadData(){
        showProgressDialog(false);
        Observable<String> observable= Api.getMemberInfo(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
                dismissProgressDialog();
            }

            @Override
            public void onNext(String s) {
                JSONObject json=JSON.parseObject(s).getJSONObject("data");
                if(json!=null){
                    JSONObject object=json.getJSONObject("MemberInfo");
                    if(null!=object){
                        memberInfo=JSON.parseObject(object.toJSONString(),MemberInfo.class);
                        highestEducation=memberInfo.getHighestEducation();
                        workType =memberInfo.getWorkType();
                        incomeRange=memberInfo.getIncomeRange();
                        cityId =memberInfo.getCity();
                        cityName=memberInfo.getCityName();
                        marriage=memberInfo.getMarriage();
                    }
                    JSONArray educationArray=json.getJSONArray("EducationList");
                    if(null!=educationArray&&educationArray.size()>0){
                        educationInfoList=new ArrayList<>();
                        for(int i=0,size=educationArray.size();i<size;i++){
                            educationInfoList.add(JSON.parseObject(educationArray.getString(i),EducationInfo.class));
                        }
                    }
                    JSONArray incomeArray=json.getJSONArray("IncomeRangeList");
                    if(null!=incomeArray&&incomeArray.size()>0){
                        incomeInfoList=new ArrayList<>();
                        for(int i=0,size=incomeArray.size();i<size;i++){
                            incomeInfoList.add(JSON.parseObject(incomeArray.getString(i),IncomeInfo.class));
                        }
                    }
                    JSONArray workTypeArray=json.getJSONArray("WorkTypeList");
                    if(null!=workTypeArray&&workTypeArray.size()>0){
                        workTypeList =new ArrayList<>();
                        for(int i=0,size=workTypeArray.size();i<size;i++){
                            workTypeList.add(JSON.parseObject(workTypeArray.getString(i),WorkType.class));
                        }
                    }
                    if(!TextUtils.isEmpty(cityName)){
                        tvChooseCity.setText(cityName);
                        tvChooseCity.setTextColor(COLOR_BLACK);
                    }
                    //学历
                    if(!TextUtils.isEmpty(highestEducation)){
                        String name=getEducationName(highestEducation);
                        if(!TextUtils.isEmpty(name)){
                            tvHighestEducation.setTextColor(COLOR_BLACK);
                            tvHighestEducation.setText(name);
                        }
                    }
                    //婚姻
                    if(marriage!=0){
                        if(marriage==1) {
                            tvMarryState.setText("已婚");
                        }else{
                            tvMarryState.setText("未婚");
                        }
                        tvMarryState.setTextColor(COLOR_BLACK);
                    }
                    //职业
                    if(!TextUtils.isEmpty(workType)){
                        String name= getWorkTypeName(workType);
                        if(!TextUtils.isEmpty(name)){
                            tvJobInformation.setText(name);
                            tvJobInformation.setTextColor(COLOR_BLACK);
                        }
                    }
                    //收入范围
                    if(!TextUtils.isEmpty(incomeRange)){
                        String name=getIncomeName(incomeRange);
                        if(!TextUtils.isEmpty(name)){
                            tvIncomeRange.setText(name);
                            tvIncomeRange.setTextColor(COLOR_BLACK);
                        }
                    }
                    dismissProgressDialog();
                }
            }
        });
    }

    //提交数据到服务器
    private void commitData(){
        showProgressDialog(false);
        Map<String,Object> params=new HashMap<>();
        params.put("ID",mApplication.getUser().getID());
        params.put("Marriage",marriage);
        params.put("HighestEducation",highestEducation);
        params.put("IncomeRange",incomeRange);
        params.put("WorkType", workType);
        params.put("City", cityId);
        Observable<String> observable=Api.updatePersonInfo(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
                dismissProgressDialog();
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject object=JSON.parseObject(s);
                if(object.getIntValue("code")==1){
                    ToastUtil.showToast("保存个人信息成功");
                }else{
                    ToastUtil.showToast(object.getString("msg"));
                }
            }
        });
    }
}
